<template>
  <div>
    <slot>
      <p class=" text-sm">
        {{ showTime }}
      </p>
    </slot>
  </div>
</template>

<script>
const EMITS_FINISH = 'finish'
const EMITS_CHANGE = 'change'
const INTERVAL_COUNT = 1000
</script>

<script setup>
import { ref, watch, onBeforeUnmount, computed } from 'vue'
import dayjs from './util'
const props = defineProps({
  // 时间戳
  time: {
    type: Number,
    required: true
  },
  // format 格式
  format: {
    type: String,
    default: 'HH:mm:ss'
  }
})

const emits = defineEmits([EMITS_FINISH, EMITS_CHANGE])
let interval
// 开始倒计时
const start = () => {
  close()
  interval = setInterval(() => {
    durtionFn()
  }, INTERVAL_COUNT)
}

const duration = ref(0)

// 倒计时的执行行为
const durtionFn = () => {
  duration.value -= INTERVAL_COUNT
  emits(EMITS_CHANGE)
  if (duration.value <= 0) {
    duration.value = 0
    emits(EMITS_FINISH)
    close()
  }
}

// 结束倒计时
const close = () => {
  if (interval) {
    clearInterval(interval)
  }
}

// 监听time开启倒计时
watch(() => props.time, (val) => {
  duration.value = val
  start()
}, { immediate: true })

// 组件销毁时，清理倒计时
onBeforeUnmount(() => {
  close()
})

// 格式化时间
const showTime = computed(() => {
  return dayjs.duration(duration.value).format(props.format)
})
</script>

<style lang="scss" scoped></style>